<!doctype html>
<html>
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1,user-scalable=no">
	<link rel="stylesheet" type="text/css" href="css/base.css">
	<title>xuluo</title>
	<style>
		*{margin:0;padding:0;font-family:'microsoft yahei';-webkit-tap-highlight-color:rgba(0,0,0,0);}
		a{text-decoration:none;outline:none;color:#666;}
		ul,li{list-style:none;}
		html,body{background: #f4f4f7;}
	</style>
</head>
<body>
	<div class="wrap" style="display: table;margin: 20px auto;text-align: center;">
		<button class="btn" id="btn" onclick="callFun()">点击调用</button>
	</div>
	<script>
		// 全兼容requestAnimationFrame
		(function() {
		    var lastTime = 0;
		    var vendors = ['webkit', 'moz'];
		    for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
		        window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
		        window.cancelAnimationFrame =
		          window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
		    }

		    if (!window.requestAnimationFrame)
		        window.requestAnimationFrame = function(callback, element) {
		            var currTime = new Date().getTime();
		            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
		            var id = window.setTimeout(function() { callback(currTime + timeToCall); },
		              timeToCall);
		            lastTime = currTime + timeToCall;
		            return id;
		        };

		    if (!window.cancelAnimationFrame)
		        window.cancelAnimationFrame = function(id) {
		            clearTimeout(id);
		        };
		}());
		// requestAnimationFrame调用
		var obj=document.querySelector('#btn'),flag='right',anim;
		obj.style.marginLeft=0;
		var callFun=function(){
			cancelAnimationFrame(anim);
			anim=requestAnimationFrame(Fun);
		};
		function Fun(){
			if(flag=='right'){
				obj.style.marginLeft=parseInt(obj.style.marginLeft)+15+'px';
				if(parseInt(obj.style.marginLeft)==300){
					console.log(parseInt(obj.style.marginLeft));
					flag='left';
				}
			}else if(flag=='left'){
				obj.style.marginLeft=parseInt(obj.style.marginLeft)-15+'px';
				if(parseInt(obj.style.marginLeft)==0){
					flag='right';
				}
			}else if(flag=='stop'){
				cancelAnimationFrame(anim);
			}
			anim=requestAnimationFrame(Fun);
		}
	</script>	
</body>
</html>